package com.client.service.impl;

import com.client.utils.RedisUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class EmailServiceImpl {
    private final JavaMailSender mailSender;
    private final RedisTemplate<String, String> redisTemplate;
    @Autowired
    RedisUtils redisUtils;
    // 发送验证码
    public void sendVerifyCode(String email) {
        String code = generateRandomCode(6); // 生成6位随机数字
        redisUtils.set("verify_code:" + email, code, 120);
        sendEmail(email, "老登儿，查收 验证码", "验证码：" + code + "，2分钟内不用就过期了喔~");
    }

    // 验证码校验
    public boolean verifyCode(String email, String userInputCode) {
        String storedCode = (String) redisUtils.get("verify_code:" + email);
        return userInputCode.equals(storedCode);
    }

    private void sendEmail(String to, String subject, String text) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("2836126390@qq.com");
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);
        mailSender.send(message);
    }

    private String generateRandomCode(int length) {
        return ThreadLocalRandom.current()
                .ints(length, 0, 10)
                .mapToObj(String::valueOf)
                .collect(Collectors.joining());
    }

}
